#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-5-16 17:38
# @Author  : jiaoxianzhong
# @File    : __init__.py.py
# @Software: PyCharm
# 初始化APScheduler
import atexit
import platform

from flask_apscheduler import APScheduler

# 初始化生成APScheduler对象
scheduler = APScheduler()


def init_scheduler(app):
    # 解决APScheduler定时任务重复执行的问题
    if platform.system() == 'Linux':
        # Linux 环境下
        fcntl = __import__("fcntl")
        f = open('scheduler.lock', 'wb')
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            scheduler.init_app(app)
            scheduler.start()
        except Exception as e:
            app.logger.error(e)
            print(e)

        def unlock():
            fcntl.flock(f, fcntl.LOCK_UN)
            f.close()

        atexit.register(unlock)
    else:
        # Window 环境下
        msvcrt = __import__('msvcrt')
        f = open('scheduler.lock', 'wb')
        try:
            msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
            scheduler.init_app(app)
            scheduler.start()
        except Exception as e:
            pass

        def _unlock_file():
            try:
                f.seek(0)
                msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
            except Exception as e:
                pass
        atexit.register(_unlock_file)
